
import * as puppeteer from 'puppeteer'
import * as util from '../util/util'
export class PuppeteerBase {

    Page: puppeteer.Page;
    constructor(Page: puppeteer.Page) {
        this.Page = Page;
    }
    async isdomsNotFound(selector: string, Opt?: puppeteer.WaitForSelectorOptions) {
        try {
            await this.Page.waitFor(selector, Opt);
        } catch (error) {
            throw ERROR.DOM_NOT_FOUND
        }
    }

    //获取单个元素
    async getdom(selector: string) {

        let doms = await this.Page.$$(selector);
        if (doms.length > 1) {
            throw ERROR.DOM_LENGTH_BEYONG_ONE;
        }
        return doms[0];
    }

    //截图
    async shot(ShotOpt: ScreenshotOpts) {
        ShotOpt.path = await util.get_shot_photo_store_path(ShotOpt.path);
        await this.Page.screenshot(ShotOpt)
    }

    async isDomExist(selector: string) {
        let length = (await this.Page.$$(selector)).length;
        if (length > 0) {
            return true
        } else {
            return false
        }
    }

    //监听请求事件
    getAllRequest() {
        let All = []
        this.Page.on('request', req => {
            All.push(req.url())
        })
        return All;
    }

    getAllResponse() {
        let All = []
        this.Page.on('response', resp => {
            All.push(resp.url())
        })
        return All;
    }
}
export class ScreenshotOpts implements puppeteer.ScreenshotOptions {
    path: string;
}
export enum ERROR {
    DOM_NOT_FOUND = "元素未找到！",
    DOM_LENGTH_BEYONG_ONE = "找到多个元素",
}